# 启动 uvicorn api:app --reload
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import time
import random

app = FastAPI()

# 模拟的数据
items = [
    {"id": 1, "name": "Item 1", "description": "Description for Item 1"},
    {"id": 2, "name": "Item 2", "description": "Description for Item 2"},
    {"id": 3, "name": "Item 3", "description": "Description for Item 3"}
]

class Item(BaseModel):
    name: str
    description: str

# 随机延迟100到800毫秒
def add_random_delay():
    delay = random.uniform(0.1, 0.5)
    time.sleep(delay)

@app.get("/items/")
def get_items():
    add_random_delay()
    return items

@app.get("/items/{item_id}")
def get_item(item_id: int):
    add_random_delay()
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.post("/items/")
def create_item(item: Item):
    add_random_delay()
    new_item = {"id": items[-1]["id"] + 1, "name": item.name, "description": item.description}
    items.append(new_item)
    return new_item

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    add_random_delay()
    for i, existing_item in enumerate(items):
        if existing_item["id"] == item_id:
            items[i] = {"id": item_id, "name": item.name, "description": item.description}
            return items[i]
    raise HTTPException(status_code=404, detail="Item not found")

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    add_random_delay()
    for i, item in enumerate(items):
        if item["id"] == item_id:
            del items[i]
            return {"message": "Item deleted successfully"}
    raise HTTPException(status_code=404, detail="Item not found")